import { createRequire } from 'node:module';

import { DEBUG_PATH,readFileBySuffixName } from '../../utils/index.mjs';

const require = createRequire(import.meta.url);
const fs = require('node:fs');
const path = require('node:path');

export function createDebugHandler(app, logger) {
  // 获取映射文件
  app.get('/debug/commands/:id', (req, res) => {
    const id = req.params.id || 'commands';
    const commandsPath = path.resolve(DEBUG_PATH, `${id}.json`);
    try {
      const data = fs.readFileSync(commandsPath, 'utf8');
      res.send({ code: 200, data, msg: 'commands.json 存在' });
    } catch (error) {
      logger.error(error);
      res.send({ code: 500, msg: 'commands.json 不存在' });
    } finally {
      res.end();
    }
  });

  // 保存文件
  app.post('/debug/save/:id', (req, res) => {
    const id = req.params.id || 'commands';
    let data = '';
    req.on('data', (chunk) => {
      data += chunk;
    });
    req.on('end', () => {
      try {
        data = JSON.parse(data); // 将JSON字符串解析成对象
        // 映射文件
        const commandsPath = path.resolve(DEBUG_PATH, `${id}.json`);
        fs.writeFileSync(commandsPath, JSON.stringify(data.commands));
        res.send({ code: 200, msg: '保存成功' });
      } catch (error) {
        logger.info(error);
        res.send({ code: 500, msg: '保存失败' });
      } finally {
        res.end();
      }
    });
  });

  // 切换指令集
  app.get('/debug/env', (req, res) => {
    const filePath = req.query.path;
    if (!filePath) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    try {
      // 判断文件是否存在
      fs.existsSync(filePath, (error) => {
        if (error) {
          logger.info(`${decodeURI(filePath)}文件不存在！`);
          // 文件不存在，向客户端发送404状态码，并发送该文件不存在的字符串
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.send({ code: 400, msg: `${filePath}文件不存在！` });
          res.end();
        }
      });
      // 使用router模块的函数
      readFileBySuffixName(filePath, fs, req, res);
    } catch (error) {
      logger.info(error);
      res.send({ code: 500, msg: '打开文件失败' });
      res.end();
    }
  });
}
